<template>
  <div class="batches-container">
    <PageHeader title="生产批次管理">
      <template #actions>
        <el-button type="primary" @click="openNewBatchDialog">新建批次</el-button>
      </template>
    </PageHeader>

    <main class="batches-content">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>批次列表</span>
            <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 150px">
              <el-option label="全部" value="" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已终止" value="aborted" />
            </el-select>
          </div>
        </template>

        <el-table :data="filteredBatches" style="width: 100%">
          <el-table-column prop="batch_number" label="批次编号" />
          <el-table-column prop="product_type" label="产品类型" />
          <el-table-column label="开始时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.start_time) }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间">
            <template #default="scope">
              {{ scope.row.end_time ? formatDateTime(scope.row.end_time) : '进行中' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getBatchStatusType(scope.row.status)">
                {{ getBatchStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="目标长度">
            <template #default="scope">
              {{ formatNumber(scope.row.target_length) }} 米
            </template>
          </el-table-column>
          <el-table-column label="实际长度">
            <template #default="scope">
              {{ formatNumber(scope.row.actual_length) }} 米
            </template>
          </el-table-column>
          <el-table-column label="完成率">
            <template #default="scope">
              <el-progress
                :percentage="getCompletionPercentage(scope.row)"
                :status="getProgressStatus(scope.row.status)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button
                size="small"
                @click="viewBatchDetails(scope.row)"
              >
                查看详情
              </el-button>
              <el-button
                v-if="scope.row.status === 'in_progress'"
                size="small"
                type="success"
                @click="completeBatch(scope.row)"
              >
                完成
              </el-button>
              <el-button
                v-if="scope.row.status === 'in_progress'"
                size="small"
                type="danger"
                @click="abortBatch(scope.row)"
              >
                终止
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 新建批次对话框 -->
      <el-dialog
        v-model="newBatchDialogVisible"
        title="新建生产批次"
        width="50%"
      >
        <el-form :model="newBatch" label-width="120px">
          <el-form-item label="批次编号">
            <el-input v-model="newBatch.batch_number" />
          </el-form-item>
          <el-form-item label="产品类型">
            <el-input v-model="newBatch.product_type" />
          </el-form-item>
          <el-form-item label="目标长度">
            <el-input-number v-model="newBatch.target_length" :min="1" :precision="2" style="width: 100%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="newBatchDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="createNewBatch">创建</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批次详情对话框 -->
      <el-dialog
        v-model="batchDetailsVisible"
        title="批次详情"
        width="70%"
      >
        <div v-if="selectedBatch">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="批次编号">{{ selectedBatch.batch_number }}</el-descriptions-item>
            <el-descriptions-item label="产品类型">{{ selectedBatch.product_type }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDateTime(selectedBatch.start_time) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ selectedBatch.end_time ? formatDateTime(selectedBatch.end_time) : '进行中' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getBatchStatusType(selectedBatch.status)">
                {{ getBatchStatusText(selectedBatch.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="完成率">
              <el-progress
                :percentage="getCompletionPercentage(selectedBatch)"
                :status="getProgressStatus(selectedBatch.status)"
              />
            </el-descriptions-item>
            <el-descriptions-item label="目标长度">{{ formatNumber(selectedBatch.target_length) }} 米</el-descriptions-item>
            <el-descriptions-item label="实际长度">{{ formatNumber(selectedBatch.actual_length) }} 米</el-descriptions-item>
          </el-descriptions>

          <div class="batch-chart-section">
            <h3>生产进度</h3>
            <div class="chart-container">
              <ECharts :options="batchChartOptions" height="300px" />
            </div>
          </div>
        </div>
      </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
// import { useDashboardStore } from '@/stores' // 暂时不需要使用 store
import { ElMessage } from 'element-plus'
import ECharts from '../components/ECharts.vue'
import PageHeader from '../components/PageHeader.vue'

// const store = useDashboardStore() // 暂时不需要使用 store
const statusFilter = ref('')
const newBatchDialogVisible = ref(false)
const batchDetailsVisible = ref(false)
const selectedBatch = ref(null)

// 新批次表单
const newBatch = ref({
  batch_number: '',
  product_type: '',
  target_length: 5000
})

// 模拟批次数据
const batches = ref([
  {
    id: 1,
    batch_number: 'B20250417001',
    product_type: 'CTC导线',
    start_time: '2025-04-16T08:00:00',
    end_time: '2025-04-16T16:30:00',
    status: 'completed',
    target_length: 5000,
    actual_length: 5120
  },
  {
    id: 2,
    batch_number: 'B20250417002',
    product_type: 'CTC导线',
    start_time: '2025-04-17T08:00:00',
    end_time: null,
    status: 'in_progress',
    target_length: 6000,
    actual_length: 2450
  },
  {
    id: 3,
    batch_number: 'B20250416001',
    product_type: 'CTC导线',
    start_time: '2025-04-15T14:00:00',
    end_time: '2025-04-15T17:30:00',
    status: 'aborted',
    target_length: 4000,
    actual_length: 1200
  }
])

// 计算属性
const filteredBatches = computed(() => {
  if (!statusFilter.value) return batches.value
  return batches.value.filter(batch => batch.status === statusFilter.value)
})

// 批次图表配置
const batchChartOptions = computed(() => {
  if (!selectedBatch.value) return {}

  const completionPercentage = getCompletionPercentage(selectedBatch.value)

  return {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        name: '生产进度',
        type: 'gauge',
        detail: {
          formatter: '{value}%',
          fontSize: 20
        },
        data: [
          {
            value: completionPercentage,
            name: '完成率'
          }
        ],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#FF6E76'],
              [0.7, '#FDDD60'],
              [1, '#7CFFB2']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'auto'
          }
        }
      }
    ]
  }
})

// 方法
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0'
  return num.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

const formatDateTime = (dateString) => {
  if (!dateString) return '无数据'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const getBatchStatusType = (status) => {
  switch (status) {
    case 'in_progress': return 'primary'
    case 'completed': return 'success'
    case 'aborted': return 'danger'
    default: return 'info'
  }
}

const getBatchStatusText = (status) => {
  switch (status) {
    case 'in_progress': return '进行中'
    case 'completed': return '已完成'
    case 'aborted': return '已终止'
    default: return '未知'
  }
}

const getProgressStatus = (status) => {
  switch (status) {
    case 'in_progress': return ''
    case 'completed': return 'success'
    case 'aborted': return 'exception'
    default: return ''
  }
}

const getCompletionPercentage = (batch) => {
  if (!batch.target_length) return 0
  const percentage = (batch.actual_length / batch.target_length) * 100
  return Math.min(Math.round(percentage), 100)
}

const openNewBatchDialog = () => {
  newBatch.value = {
    batch_number: `B${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(batches.value.length + 1).padStart(3, '0')}`,
    product_type: 'CTC导线',
    target_length: 5000
  }
  newBatchDialogVisible.value = true
}

const createNewBatch = () => {
  const newBatchData = {
    id: batches.value.length + 1,
    ...newBatch.value,
    start_time: new Date().toISOString(),
    end_time: null,
    status: 'in_progress',
    actual_length: 0
  }

  batches.value.unshift(newBatchData)
  ElMessage.success('批次创建成功')
  newBatchDialogVisible.value = false
}

const viewBatchDetails = (batch) => {
  selectedBatch.value = batch
  batchDetailsVisible.value = true
}

const completeBatch = (batch) => {
  const index = batches.value.findIndex(b => b.id === batch.id)
  if (index !== -1) {
    batches.value[index].status = 'completed'
    batches.value[index].end_time = new Date().toISOString()
    ElMessage.success('批次已完成')
  }
}

const abortBatch = (batch) => {
  const index = batches.value.findIndex(b => b.id === batch.id)
  if (index !== -1) {
    batches.value[index].status = 'aborted'
    batches.value[index].end_time = new Date().toISOString()
    ElMessage.warning('批次已终止')
  }
}

// 生命周期钩子
onMounted(() => {
  // 在实际应用中，这里会从API获取批次数据
  // store.fetchBatches()
})
</script>

<style scoped>
.batches-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

/* 使用共享的 PageHeader 组件样式 */

.batches-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-chart-section {
  margin-top: 20px;
}

.batch-chart-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.chart-container {
  height: 300px;
}
</style>
